package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.VoicePublish;
import com.tanhua.domain.vo.QueryVoiceVo;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.VoicePublishApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class VoiceService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Reference
    private VoicePublishApi voicePublishApi;

    @Reference
    private UserInfoApi userInfoApi;


    /**
     * 保存语音
     *
     * @param soundFile
     */
    public void saveVoice(MultipartFile soundFile) {
        try {
            //获得当前用户id
            Long userId = UserHolder.getUserId();
            // redis的key名:
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String todayDate = simpleDateFormat.format(new Date());
            String voiceKey = "voice_publish_" + userId + todayDate;

            // 获得发送次数:
            String redisCount = redisTemplate.opsForValue().get(voiceKey);
            int count = 0;
            if (redisCount == null) {
                count++;
            } else {
                count = Integer.parseInt(redisCount);
                if (count > 2) {
                    //大于3次 抛出一个 今日超过3次 的异常
                    throw new TanHuaException("今日发送语音次数已超过3次");
                }
                count++;
            }

            // 上传语音文件:
            String originalFilename = soundFile.getOriginalFilename();
            //截取文件后缀名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //上传语音到fdfs
            StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), suffix, null);
            //获取语音的完成路径
            String soundUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

            // 发送消息到rocketMQ队列:
            Map<String, Object> message = new HashMap<>();
            message.put("userId", userId);
            message.put("soundUrl", soundUrl);
            rocketMQTemplate.convertAndSend("tanhua_voice_topic", message);

            // redis中存入当前次数,有效时间1天
            redisTemplate.opsForValue().set(voiceKey, String.valueOf(count), 1, TimeUnit.DAYS);
            log.debug("*******************当前是第*{}*次发送语音********************", count);

        } catch (IOException e) {
            e.printStackTrace();
            throw new TanHuaException("服务器忙,请稍后再试");
        }
    }

    /**
     * 推荐语音
     *
     * @return
     */
    public QueryVoiceVo queryVoice() {
        Long currentUserId = UserHolder.getUserId();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String todayDate = simpleDateFormat.format(new Date());
        String voiceKey = "query_count_" + currentUserId + "_" + todayDate;
        String redisCount = redisTemplate.opsForValue().get(voiceKey);
        int count;
        if (redisCount == null) {
            count = 4;
        } else {
            count = Integer.parseInt(redisCount);
            if (count <= 0) throw new TanHuaException("您今日已经接收语音超过3次");
        }

        //对查出的推荐语音动态进行前端数据封装并返回
        VoicePublish publish = voicePublishApi.queryVoice(currentUserId);

        //记录数减一
        count--;
        //记录查询次数存入redis库
        redisTemplate.opsForValue().set(voiceKey, String.valueOf(count), 1, TimeUnit.DAYS);

        //返回数据到前端
        QueryVoiceVo queryVoiceVo = null;
        if (publish != null) {
            queryVoiceVo = new QueryVoiceVo();
            Long voiceUserId = publish.getUserId().longValue();
            UserInfo userInfo = userInfoApi.queryUserInfo(voiceUserId);
            //把属性拷贝和封装到对象中
            BeanUtils.copyProperties(userInfo, queryVoiceVo);
            queryVoiceVo.setId(publish.getNum());//返回语音动态序号
            queryVoiceVo.setSoundUrl(publish.getUrl());
            queryVoiceVo.setRemainingTimes(count);
        }

        return queryVoiceVo;
    }

    /**
     * 喜欢语音
     *
     * @param num
     */
    public void saveVoiceLove(String num) {
        //获取用户ID
        Integer userId = UserHolder.getUserId().intValue();
        // 发送消息到rocketMQ队列:
        Map<String, Object> message = new HashMap<>();
        message.put("userId", userId);
        message.put("likeNum", num);
        rocketMQTemplate.convertAndSend("tanhua_voice_like_topic", message);
    }

    /**
     * 不喜欢语音
     *
     * @param num
     */
    public void removeVoiceLove(String num) {
        //获取用户ID
        Integer userId = UserHolder.getUserId().intValue();
        // 发送消息到rocketMQ队列:
        Map<String, Object> message = new HashMap<>();
        message.put("userId", userId);
        message.put("likeNum", num);
        rocketMQTemplate.convertAndSend("tanhua_voice_dislike_topic", message);
    }
}
